package consumer

import (
	"encoding/json"
	"github.com/streadway/amqp"
	"go.uber.org/zap"
	"niu-video/app/consts"
	"niu-video/app/model"
	"niu-video/app/repository"
	"niu-video/pkg/logger"
	"niu-video/pkg/rabbitmq"
)

func registerCollectConsumer() {
	// 新建连接
	rabbit := rabbitmq.NewRabbitMQ(consts.RABBITMQ_COLLECT_EXCHANGE, consts.RABBITMQ_COLLECT_ROUTE, consts.RABBITMQ_COLLECT_QUEUE)
	// 执行消费
	rabbit.Consume(func(d amqp.Delivery) (err error) {
		var collectMessage model.CollectMessage
		if err := json.Unmarshal(d.Body, &collectMessage); err != nil {
			logger.Info("rabbitmq", zap.String("collect", "json解析失败！"))
		}
		switch collectMessage.ActionType {
		case 1:
			err = repository.CollectRepository.Create(&model.UserCollect{
				VideoID: collectMessage.VideoID,
				UserID:  collectMessage.UserID,
			})
			if err != nil {
				logger.Error("rabbitmq", zap.String("create", err.Error()))
				return err
			}
		case 2:
			err = repository.CollectRepository.Delete(collectMessage.VideoID, collectMessage.UserID)
			if err != nil {
				logger.Error("rabbitmq", zap.String("delete", err.Error()))
				return err
			}
		}
		return err
	})
}
